<template>
  <div v-loading="loading"
       element-loading-text="拼命部署中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <!--    ------------------------------------------------------------------------------------------------    -->
    <!--    登录弹窗-->
    <el-dialog
        class="login-dialog"
        @opened="openedLogin"
        title="登录到EasyApi"
        :show-close="false"
        :visible.sync="showLoginView"
        :close-on-click-modal="false"
        width="30%">
      <div class="login-dialog">
        <div style="margin: 0 auto;max-width: 250px">
          <h4>用户名</h4>
          <el-input ref="userInput" prefix-icon="el-icon-user" placeholder="请输入用户名"
                    v-model="loginData.username"></el-input>
          <h4 style="margin-top: 20px;">密码</h4>
          <el-input prefix-icon="el-icon-magic-stick" @keyup.enter.native="loginMethod" placeholder="请输入密码"
                    type="password" v-model="loginData.password"></el-input>
          <div class="controller">
            <el-button @click="loginMethod" type="success" style="width: 100%;">登陆</el-button>
          </div>
          <h5 style="color: #409EFF;margin: 5px 0;"><span class="el-icon-magic-stick"></span> 没有账号？请联系管理员获取账号</h5>
          <h5 style="color: #409EFF;margin: 5px 0;"><span class="el-icon-magic-stick"></span> 管理员账号密码默认为admin</h5>
        </div>

      </div>
    </el-dialog>
    <!--    修改密码弹窗-->
    <el-dialog
        title="修改密码"
        show-close
        :visible.sync="showUpdatePassWord"
        width="30%">
      <div class="update-password-dialog">
        <h4 style="margin-top: 20px;">新密码</h4>
        <el-input placeholder="请输入新密码" v-model="updatePassWordData.password"></el-input>
        <h4 style="margin-top: 20px;">确认新密码</h4>
        <el-input placeholder="请确认新密码" v-model="updatePassWordData.repassword"></el-input>
        <el-button class="commit-update-password" type="danger" @click="updatePassWordCommit">确认修改</el-button>
      </div>
    </el-dialog>
    <!--    用户管理弹窗-->
    <el-dialog
        title="用户管理"
        fullscreen
        v-if="showUserManager"
        :visible.sync="showUserManager"
        :close-on-click-modal="false">
      <div class="user-manager-dialog">
        <el-dialog
            title="导出用户数据"
            append-to-body
            :visible.sync="showExport"
            width="50%">
          <div class="export">
            <download-excel
                class="export-excel-wrapper"
                :data="searchUserResultData"
                :fields="userFields"
                :name="'导出用户'+new Date().toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.')+'.xls'">
              <div class="view">
                <el-button type="danger" size="small">导出EXCEL</el-button>
              </div>
            </download-excel>
            <json-viewer :expand-depth='5' class="show-user-by-json" copyable
                         :value="searchUserResultData"></json-viewer>
          </div>
        </el-dialog>
        <el-dialog
            title="导入用户数据"
            append-to-body
            :visible.sync="showImport"
            :before-close="importDialogBeforeClose"
            width="50%">
          <div class="export">
            <el-dialog
                title="JSON预览"
                show-close
                append-to-body
                :visible.sync="showYlView"
                width="50%">
              <div class="update-password-dialog">
                <json-viewer :expand-depth='5' class="show-user-by-json" copyable
                             :value="stringToJson(importData)"></json-viewer>
              </div>
            </el-dialog>
            <div class="input-controller">
              <el-upload
                  class="upload-demo"
                  action=""
                  ref="upload"
                  accept=".xls,.xlsx"
                  :on-change="loadExcelFile"
                  :show-file-list="false"
                  :auto-upload="false"
                  multiple
                  :limit="1">
                <el-button type="danger" size="small">从EXCEL加载数据</el-button>
              </el-upload>
              <el-button style="margin: 0 5px" type="danger" @click="showYlView = !showYlView" size="small">预览JSON数据
              </el-button>
              <el-button style="margin: 0 5px" type="warning" @click="importRequest" size="small">确定导入</el-button>
            </div>
            <h5 style="margin: 5px;color: #409EFF">通过EXCEL导入数据，EXCEL的格式需和导出数据保持一致</h5>

            <el-input style="margin: 5px 0;" v-model="importData" clearable placeholder="请粘贴数据在此"
                      type="textarea"
                      :autosize="{ minRows: 15, maxRows: 20}"></el-input>
          </div>
        </el-dialog>

        <el-dialog
            :title="'用户信息'+userInfoData.username"
            show-close
            append-to-body
            width="50%"
            :visible.sync="showUserInfo">
          <div class="user-info-dialog">
            <div>
              <div v-for="item in userTable" v-if="item.showInTable || item.key ==='password'" class="user-info-item">
                <h5 class="item-name">{{item.desc}}:</h5>
                <h5 class="item-value" :class="userInfoData[item.key]?'':'unset'">
                  {{userInfoData[item.key]?userInfoData[item.key]:'未设置'}}</h5>
              </div>
              <div class="u-auth-p">
                <h5>已拥有权限：</h5>
                <div class="auths">
                  <h5 class="auths-item" v-for="item in userInfoData.auths">
                    {{authsMap[item].moudleRemark+'('+item+')'}}</h5>
                </div>
              </div>
              <div class="u-auth-p">
                <h5>未拥有权限：</h5>
                <div class="auths">
                  <h5 class="auths-item no-auth"
                      v-if="userInfoData.auths&&userInfoData.auths.indexOf(item.authCode)==-1" v-for="item in authsMap">
                    {{item.moudleRemark+'('+item.authCode+')'}}</h5>
                </div>
              </div>
            </div>
          </div>
        </el-dialog>
        <div class="top-search">
          <el-input size="mini" @keyup.enter.native = "searchUser(searchUserData)" placeholder="请输入搜索内容" v-model="searchUserData" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="searchUser(searchUserData)">搜索</el-button>
            <el-button slot="append" icon="el-icon-refresh" @click="resetSearch(searchUserData)">重置</el-button>
            <el-button slot="append" icon="el-icon-plus" size="mini" type="danger" @click="addUser('add')">添加用户
            </el-button>
            <el-button slot="append" icon="el-icon-upload2" size="mini" type="danger" @click="exportUser('add')">导出
            </el-button>
            <el-button slot="append" icon="el-icon-download" size="mini" type="danger" @click="importUser('add')">导入
            </el-button>
          </el-input>
        </div>
        <el-table
            border
            :data="searchUserResultData"
            size="mini"
            style="width: 100%">
          <el-table-column
              v-for="item in userTable"
              :fixed="['username'].indexOf(item.key)!==-1"
              v-if="item.showInTable"
              :prop="item.key"
              :label="item.desc"
              width="150">
          </el-table-column>
          <el-table-column
              prop="superAdmin"
              label="身份"
              width="150">
            <template slot-scope="scope">
              <p>{{scope.row.superAdmin===1?'超级管理员':'普通用户'}}</p>
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="130">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="showUserInfoClick(scope)">查看</el-button>
              <el-button type="text" size="small" @click="updateUserInfoClick(scope)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteUser(scope.row.username)"><span style="color: #ff0000">删除</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-dialog>
    <!--    编辑用户-->
    <el-dialog
        :title="userEditType==='add'?'添加用户':'编辑用户'"
        show-close
        :visible.sync="showUpdateUser"
        width="50%">
      <div class="update-password-dialog">
        <h4 style="margin-top: 20px;">用户名</h4>
        <el-input placeholder="" v-model="updateUserData.username"></el-input>
        <h4 style="margin-top: 20px;">密码</h4>
        <el-input placeholder="" v-model="updateUserData.password"></el-input>
        <h4 style="margin-top: 20px;">权限组</h4>
        <el-radio-group style="margin: 10px 0;" v-model="updateUserData.superAdmin">
          <el-radio :label="1">超级管理员</el-radio>
          <el-radio :label="0">普通用户</el-radio>
        </el-radio-group>
        <h4 style="margin-top: 20px;">权限【选填】</h4>
        <el-checkbox-group v-model="updateUserData.auths">
          <el-checkbox style="min-width: 120px" :label="item.authCode" v-for="item in auths">
            <template>
              <div>{{item.moudleRemark}}</div>
            </template>
          </el-checkbox>
        </el-checkbox-group>
        <el-button class="commit-update-password" type="warning" @click="commitEdit">
          {{userEditType==='add'?'确认添加':'确认修改'}}
        </el-button>
        <br>
        <el-button class="commit-update-password" type="danger" v-if="userEditType==='edit'"
                   @click="deleteUser(updateUserData.username)">删除用户
        </el-button>
      </div>
    </el-dialog>
    <!--    ------------------------------------------------------------------------------------------------    -->
    <!-- 选中某个接口后 -->
    <sidebar  ref="mySidebar" @getControllers="getControllers" @openList="openList" @chooseSid="chooseSid" :list="list"
             class="sidebar-container" v-if="isLogin"/>
    <div class="main-container" v-if="isLogin">
      <header class="index_header">
        <div class="top">
          <div class="right">
            <div class="tag-version">
              免费版
              <span></span>
            </div>
          </div>
          <div class="left">
            <!-- Easy-Api -->
            <img src="../assets/images/favicon.png" alt="">
          </div>

          <div>
            <div class="login login-title" v-if="isLogin">
              <el-dropdown trigger="click" @command="commandListen">
                <h3>
                <span style="color: #ffffff">
                  {{loginInfo.userInfo.username}}
                  <span class="el-icon-caret-bottom" style="margin: 0 5px;"></span>
                </span>
                  <span style="color: #409EFF;">[{{loginInfo.userInfo.superAdmin===1?'超级管理员':'普通用户'}}]</span>
                </h3>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item icon="el-icon-user" command="user-manager"
                                    v-if="loginInfo&&loginInfo.userInfo&&loginInfo.userInfo.superAdmin">
                    <span>用户管理</span></el-dropdown-item>
                  <el-dropdown-item icon="el-icon-edit" command="change-password"><span>修改密码</span></el-dropdown-item>
                  <el-dropdown-item icon="el-icon-sort" command="change-login"><span>切换用户</span></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div class="ulogin login-title" @click="showLogin" v-else>
              <h5 class="hit">您还未登录，立即登录？</h5>
            </div>
          </div>
        </div>

      </header>
      <navbar ref="myNav" @changeTop="changeTop" :name="activeName" @copy="copy" @deleteRightTop="deleteRightTop"
              @deleteLeftTop="deleteLeftTop" @deleteTab="deleteTab" :tabList="tabList"/>
      <appMain ref="mychild" res v-show="!showIndex" :InitInfo="InitInfo"/>
      <div v-show="showIndex" class="app-main indexPage">
        <el-form label-position="right" label-width="200px" :model="indexData" v-if="this.$checkRoles([20001])">
          <el-form-item label="文档标题：">
            {{mainInfo.title}}
          </el-form-item>
          <el-form-item label="文档说明：">
            <div v-html="mainInfo.remark"></div>
            <!-- <textarea :value="mainInfo.remark"></textarea> -->
          </el-form-item>
          <el-form-item label="请求环境：">
            <el-form class="demo-form-inline">
              <el-form-item v-for="(item,index) in mainInfo.requestHost" :key="index">
                {{item.name}} ： {{item.host}}
              </el-form-item>
            </el-form>
          </el-form-item>
          <el-form-item label="">
            <el-button @click="edit" size="small" type="success" v-if="this.$checkRoles([20201])">修改</el-button>
            <el-button @click="editDiog" size="small" v-if="this.$checkRoles([20002])">查看返回参数外包装</el-button>
            <el-button @click="addInter" type="primary" size="small" v-if="this.$checkRoles([10002])">同步所有接口</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <editIndex ref="myEditIndex" @edit="edit" :show="editShow"/>
    <outDigo v-if="isLogin" @editDiog="editDiog" :show="digShow"/>
    <el-dialog :before-close="close" title="" width="30%" :visible.sync="interShow">
      <el-form label-width="80px" label-position="right" :model="interData">
        <el-form-item label="IP+端口">
          <el-input size="small" class="input_class" v-model="interData.address" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input size="small" class="input_class" v-model="interData.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input size="small" class="input_class" type="password" v-model="interData.password"
                    auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="interEnter">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {appMain, navbar, sidebar, editIndex, outDigo} from './components/index.js'
  import {dataFormation} from '@/public'
  import {GET, POST} from '@/api/request' //request
  import {requestData} from '@/api'
  import {testReauest} from '@/config/index.js'
  import {MD5} from '@/public/dense/MD5.js'
  import {Message} from 'element-ui'
  import JsonViewer from 'vue-json-viewer';
  import Ptree from "./components/Ptree";
  import XLSX from 'xlsx'

  export default {
    name: 'home',
    data() {
      return {
        loginData: {//登录数据
          username: "",
          password: "",
        },
        loginInfo: {//登录信息数据
          userInfo: {}
        },
        updatePassWordData: {//修改密码数据
          password: "",
          repassword: ""
        },
        showLoginView: false,//是否显示登陆窗口
        isLogin: false,//是否已登录
        showUpdatePassWord: false,//是否显示修改密码弹窗
        showUserManager: false,//是否显示修改密码弹窗
        searchUserData: "",//查找用户值
        searchUserResultData: [],//查找用户返回值
        showUserInfo: false,//显示用户详情
        userInfoData: {},//显示用户详情数据
        auths: [],//已知权限列表
        authsMap: {},//已知权限列表 keyValue
        showUpdateUser: false,//显示编辑用户
        userEditType: "edit",//编辑用户操作类型
        showExport: false,//显示导出窗口
        showImport: false,//显示导入窗口
        importData: "",//显示导入数据
        showYlView: false,//显示隐藏JSON预览
        userFields: {//导出表格表头
          "用户名": "username",
          "密码": "password",
          "是否是管理员": "superAdmin",
          "备注": "remark",
          "权限列表": {
            field: "auths",
            callback: value => {
              return `[${value}]`;
            }
          }
        },
        updateUserData: {
          username: "",
          password: "",
          auths: [],
          superAdmin: 0
        },//显示编辑用户
        userTable: [
          {key: 'id', desc: "ID", otherDesc: "ID", showInTable: false},
          {key: 'username', desc: "用户名", otherDesc: "用户名", showInTable: true},
          {key: 'password', desc: "密码", otherDesc: "密码", showInTable: false},
          {key: 'createTime', desc: "创建时间", otherDesc: "创建时间", showInTable: true},
          {key: 'updateTime', desc: "更新时间", otherDesc: "更新时间", showInTable: false},
          {key: 'superAdmin', desc: "身份", otherDesc: "身份", showInTable: false},
          {key: 'deleted', desc: "是否已删除", otherDesc: "是否已删除", showInTable: false},
          {key: 'auths', desc: "权限列表", otherDesc: "权限列表", showInTable: false},
          {key: 'remark', desc: "备注", otherDesc: "备注", showInTable: true}
        ],
        //---------------------------------------【上方】kele新增
        indexData: {}, //首页信息
        activeName: '0',
        //顶部导航
        mainInfo: {},
        editShow: false,
        digShow: false,
        tabList: [
          {
            title: '首页'
          }
        ],
        InitInfo: {  //基本信息

        },
        interData: {},//同步接口参数
        showIndex: true,//是否展示首页
        //左侧导航栏数据
        list: [],
        interShow: false,
        loading: false
      }
    },
    components: {
      appMain, navbar, sidebar, editIndex, outDigo, JsonViewer
    },
    created() {

    },
    mounted: function () {
      //--------------------------- 下方kele新增
      this.loadLogin()//加载登录信息
      //--------------------------------------

    },
    computed: {},
    methods: {
      stringToJson(data) {
        try {
          return JSON.parse(data)
        } catch (e) {
          return {}
        }
      },
      openedLogin() {
        this.$refs["userInput"].focus()
      },
      //提交用户添加/编辑操作
      commitEdit() {
        if (!(this.updateUserData.username && this.updateUserData.username.length >= 3)) {
          Message.error("用户名不能为空且长度>=3")
          return
        }
        if (this.userEditType === 'add' && !(this.updateUserData.password && this.updateUserData.password.length >= 3)) {
          Message.error("密码不能为空且长度>=3")
          return
        }
        this.$confirm("确认" + ((this.userEditType === 'add') ? '添加用户' : '修改用户') + this.updateUserData.username + "吗?", '确认修改密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.userEditType === 'add') {
            //添加用户
            let result = requestData(4, "/addUser", this.updateUserData).then(res => {
              Message.success("添加" + this.updateUserData.username + "用户成功")
              this.resetSearch(this.searchUserData)
            }).catch(e => {

            })
          } else if (this.userEditType === 'edit') {
            //编辑用户操作
            //更新用户
            let result = requestData(4, "/updateUser", this.updateUserData).then(res => {
              Message.success("更新" + this.updateUserData.username + "用户成功")
            }).catch(e => {

            })
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //发送导入请求
      importRequest() {

        this.$confirm('确认导入用户吗？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log("请求数据",)
          let upData = {}
          try {
            upData = JSON.parse(this.importData)
          } catch (e) {
            Message.error("数据格式不符合JSON规范")
            return
          }
          if (upData instanceof Array)
            requestData(4, "/importUsers", {"json":JSON.stringify(upData)}).then(res => {
              Message.success("导入成功")
            }).catch(e => {

            })
          else Message.error("数据格式不符合JSON规范")
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });

      },
      //获取已知权限列表
      getAuths() {
        let result = requestData(4, "/getAuths", {}).then(res => {
          this.auths = res
          res.forEach(item => {
            this.authsMap[item.authCode] = item
          })
        }).catch(e => {

        })
      },
      //从Excel载入数据
      loadExcelFile(file, fileList) {
        console.log("file", file);
        console.log("fileList", fileList);
        let files = {0: file.raw}
        this.readExcel(files);
      },
      //上传窗口关闭
      importDialogBeforeClose(){
        this.importData = ""
        this.showImport = false
      },
      //表格解析
      readExcel(files) {
        let that = this;
        if (files.length <= 0) {
          return false;
        } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
          Message.error('上传格式不正确，请上传xls或者xlsx格式');
          return false;
        }

        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            //读取表下标
            const name = workbook.SheetNames[0];
            const resultData = XLSX.utils.sheet_to_json(workbook.Sheets[name]);//生成json表格内容
            console.log(resultData);
            let tempData = []
            resultData.forEach(item => {
              console.log(item);
              let temp = {}
              item["权限列表"] = JSON.parse(item["权限列表"])
              Object.keys(item).forEach(itemIn => {
                temp[that.userFields[itemIn]] = item[itemIn]
              })
              tempData.push(temp)
            })

            console.log("tempData", tempData)

            that.importData = JSON.stringify(resultData)
            this.$refs.upload.clearFiles();
          } catch (e) {
            return false;
          }
        };
        fileReader.readAsBinaryString(files[0]);
      },
      //删除用户
      deleteUser(username) {
        this.$confirm('确认删除用户[' + username + ']吗？此操作不可逆', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //密码修改操作
          let result = requestData(4, "/delUser", {
            username: username
          }).then(res => {
            Message.success("用户已成功删除")
            this.resetSearch(this.searchUserData)
          }).catch(e => {

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      //导出用户数据按钮
      exportUser(data) {
        //初始化编辑框
        this.showExport = true
      },
      importUser(data) {
        //初始化编辑框
        this.showImport = true
      },
      //添加用户事件
      addUser(editType) {
        //初始化编辑框
        this.showUpdateUser = true
        this.updateUserData = {
          username: "",
          password: "",
          auths: [],
          superAdmin: 0
        }
        this.userEditType = editType
      },
      //更新用户信息
      updateUserInfoClick(scope) {
        this.addUser("edit")
        this.updateUserData["username"] = scope.row.username
        // this.updateUserData["password"] = scope.row.password
        this.updateUserData["superAdmin"] = scope.row.superAdmin
        this.updateUserData["auths"] = scope.row.auths
      },
      //显示用户信息事件
      showUserInfoClick(scope) {
        this.showUserInfo = true
        this.userInfoData = scope.row
      },
      //充值搜索
      resetSearch() {
        this.searchUserData = ""
        this.searchUser("")
        Message.success("操作成功")
      },
      //查找用户
      searchUser(data) {
        let result = requestData(4, "/findUser", {
          username: data
        }).then(res => {
          this.searchUserResultData = res
          this.getAuths()//获取权限列表
        }).catch(e => {

        })
      },
      //提交密码修改
      updatePassWordCommit() {
        //检测密码规范
        if (!(this.updatePassWordData.password && this.updatePassWordData.repassword)) {
          Message.error("密码不能为空")
          return
        }
        if (this.updatePassWordData.password.length < 5) {
          Message.error("密码长度不能小于5")
          return
        }
        if (this.updatePassWordData.password.length < 5) {
          Message.error("密码长度不能小于5")
          return
        }
        if (this.updatePassWordData.password !== (this.updatePassWordData.repassword)) {
          Message.error("密码输入不一致")
          return
        }
        this.$confirm('确认修改您的密码吗？此操作不可逆', '确认修改密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //密码修改操作
          let result = requestData(4, "/updatePassword", {
            password: this.updatePassWordData.password
          }).then(res => {
            Message.success("密码修改成功")
            this.showUpdatePassWord = false
            this.updatePassWordData = {//修改密码数据
              password: "",
              repassword: ""
            }
          }).catch(e => {

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //下拉菜单事件
      commandListen(command) {
        if (command === "change-password")
          this.clickUpdatePassWord();
        if (command === "user-manager")
          this.clickUserManager();
        if (command === "me-info") {
          //个人信息

        }
        if (command === "change-login")
          this.$confirm('此操作将清除浏览器当前用户登录信息？是否继续？', '确认切换用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            //密码修改操作
            this.changeLogin();
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
      },
      //修改密码事件
      clickUpdatePassWord() {
        this.showUpdatePassWord = true
      },
      //用户管理事件
      clickUserManager() {
        this.showUserManager = true
        //默认搜索全部
        this.searchUser("")
      },
      //切换登录
      changeLogin() {
        sessionStorage.clear()
        this.$meInfo = {}
        this.loginInfo.userInfo = {}
        this.isLogin = false
        this.showLoginView = true
      },
      //加载登录信息
      loadLogin() {
        let temp = sessionStorage.getItem("USER_INFO")
        if (temp) {
          this.loginInfo.userInfo = JSON.parse(temp)
          this.$meInfo = this.loginInfo.userInfo
          this.$meInfo.isAdmin = this.loginInfo.userInfo.superAdmin
          this.isLogin = true
          Message.success("获取登录信息成功")
          this.init() //首页接口
          this.initUser() //首页接口
          this.getControllers() //侧边栏接口t
        } else {
          this.showLogin()
        }
      },
      //登录成功
      loginSuccess(res) {
        //登录
        this.loginInfo.userInfo = res
        this.$meInfo = this.loginInfo.userInfo
        this.$meInfo.isAdmin = this.loginInfo.userInfo.superAdmin
        //存储登陆结果
        sessionStorage.setItem("USER_INFO", JSON.stringify(res))
        sessionStorage.setItem("IS_ADMIN", res.superAdmin == 1)
        this.$router.go(0)

        // this.isLogin = true
        // this.showLoginView = false
      },
      //登陆按钮
      loginMethod() {
        let that = this
        let res = requestData(4, "/login", this.loginData).then(res => {
          //存储用户名密码用于自动登陆
          sessionStorage.setItem("USER_AOTU", JSON.stringify(this.loginData));

          Message.success("登陆成功")
          this.loginData = {//重置登录数据
            username: "",
            password: "",
          };
          console.info("登陆结果", res)
          this.loginSuccess(res)
        }).catch(e => {
        })
      },
      //登陆窗口关闭前钩子
      loginViewCloseBefore() {

      },
      //显示登陆
      showLogin() {
        this.showLoginView = true
      },
      //--------------------------------
      addInter() {
        this.interData = {}
        this.interShow = true
      },
      close() {  //关闭同步弹窗
        this.interShow = false
      },
      async interEnter() {
        let data = this.interData
        this.interShow = false
        this.loading = true
        let res = requestData(2, '/manualSyncAll', data).then(res => {
          this.loading = false
        }).catch(err => {
          this.loading = false
          this.interShow = true
        })
      },
      copy(index) {
        // console.log(this.tabList[index])
        // console.log(this.InitInfo)
        let url = JSON.stringify(this.InitInfo)
        // let url = '我爱你';
        let oInput = document.createElement('input');
        oInput.value = url;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message.success('复制成功')
        oInput.remove()
      },
      editDiog() {
        this.digShow = !this.digShow
      },
      chooseUrl(item) {
        localStorage.trueRequestUrl = item.host
      },
      changeTop(activeName, oldActiveName) {  //顶部选择
        // console.log(activeName,oldActiveName,111)
        // console.log(this.tabList[oldActiveName])
        if (oldActiveName && this.oldActiveName != 0) {
          if (!this.tabList[oldActiveName]) return
          this.tabList[oldActiveName].requestList = this.$refs.mychild.requestList ? this.$refs.mychild.requestList : []
          this.tabList[oldActiveName].request_json = this.$refs.mychild.request_json ? this.$refs.mychild.request_json : ''
          this.tabList[oldActiveName].requestRendData = this.$refs.mychild.requestRendData ? this.$refs.mychild.requestRendData : {}
          this.tabList[oldActiveName].inteMockData = this.$refs.mychild.inteMockData ? this.$refs.mychild.inteMockData : {}
        }
        if (activeName == 0) {
          this.showIndex = true
        } else {
          this.showIndex = false
        }
        if (activeName != this.activeName) {
          this.activeName = activeName
          this.InitInfo = this.tabList[activeName * 1]
          if (activeName != 0) this.getRequestParam(this.tabList[activeName])
        }
      },
      //修改配置信息
      edit(num) {
        this.editShow = !this.editShow
        if (num) this.init()
      },
      openList(data) { //打开菜单获取二级list
        let newData = this.list[data.index]
        newData.children = data.children
        this.list[data.index] = newData
        this.$set(this.list, data.index, newData)
      },
      initUser() {
        if (sessionStorage.getItem("USER_INFO"))
          this.loginInfo.userInfo = JSON.parse(sessionStorage.getItem("USER_INFO"))
      },
      //测试接口
      async init(url, path, id) {
        let res = await requestData(2, '/getInfo', {})
        if (!res.requestHost.length) res.requestHost.push({})
        this.mainInfo = res
        localStorage.host = JSON.stringify(res.requestHost)
        this.$refs.myEditIndex.mainInfo = res
      },
      async getControllers(text) {
        let res
        if (!text) {
          res = await requestData(2, '/getControllers', {})
        } else {
          res = await POST('/findInterfaces', {text: text})
        }
        this.list = res
      },
      chooseRepeat(item) { //选中已有的
        let index = this.isRepeat(item.title, 1)
        this.$refs.myNav.getActiveIndex(index * 1, 1)
      },
      //选中菜单后
      async chooseSid(item) {
        this.InitInfo = item
        let flag = await this.isRepeat(item.title)
        if (!flag) return this.chooseRepeat(item)
        this.tabList.push(item)
        this.activeName = (this.tabList.length - 1) + ''
        this.$refs.myNav.getActiveIndex(this.activeName * 1)
        this.getRequestParam()
        this.showIndex = false
      },
      //删除某个tab
      deleteTab(index) {  //type==1 删除左侧  type == 2删除右侧
        // console.log(index)
        this.tabList.splice(index, 1)
        if (index == 1) {
          this.showIndex = true
        }
      },
      deleteLeftTop(name) {
        let newIndex = name
        let newName = this.tabList[name].title
        this.tabList = this.tabList.filter((val, index, item) => {
          return index == 0 || index >= name
        });
        this.tabList.map((item, index) => {
          if (newName == item.title) {
            newIndex = index
          }
        })
        this.activeName = newIndex + ''
        this.$refs.myNav.getActiveIndex(this.activeName * 1)
      },
      deleteRightTop(name) {
        // console.log(index)
        let newIndex = name
        let newName = this.tabList[name].title
        this.tabList = this.tabList.filter((val, index, item) => {
          return index == 0 || index <= name
        });
        this.tabList.map((item, index) => {
          if (newName == item.title) {
            newIndex = index
          }
        })
        this.activeName = newIndex + ''
        this.$refs.myNav.getActiveIndex(this.activeName * 1)
      },
      //获取请求参数
      async getRequestParam(oldData) {
        let requestResData, responseData, inteMockData
        let data = this.InitInfo
        if (oldData && oldData.requestList) {  //有缓存数据
          requestResData = oldData
          this.$refs.mychild.renderData(requestResData, 1);
          this.$refs.mychild.createdInit(1)
        } else {
          requestResData = await requestData(2, '/getRequestParam', {requestParamName: data.request_param_name})
          inteMockData = await requestData(2, '/getMock', {responseParamName: data.response_param_name})
          this.$refs.mychild.renderData(requestResData);
          this.$refs.mychild.getInteMockDataData(JSON.stringify(inteMockData, null, 4));
          this.$refs.mychild.createdInit()
        }
        responseData = await requestData(2, '/getResponseParam', {responseParamName: data.response_param_name})
        this.$refs.mychild.getResponse(responseData);
      },
      //判断是否重复
      isRepeat(title, type) {
        let flag = true
        let index
        let data = this.tabList
        for (let i = 0; i < data.length; i++) {
          if (title == data[i].title) {
            flag = false
            index = i
            break
          }
        }
        if (type) {
          return index
        } else {
          return flag
        }
      },
    }
  }
</script>
<style lang="scss" scope>
  .indexPage {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  // .index_header{
  //   position:fixed;
  //   top:0;
  // }
  .input_class {
    width: 200px;
  }
</style>